import asyncio
import websockets
import struct
import subprocess

# 房间列表，房间内参数：人数；房间号(端口号)
room_list=[]

# 开放端口号
PublicHostList=[80]

# 活跃的房间
new_rooms=[]

# WebSocket服务器处理客户端连接的异步函数
async def echo(websocket):
    try:
        # 异步接收客户端发送的数据
        async for data in websocket:
            # 检查进程
            for index,new_room in enumerate(new_rooms):
                if new_room.poll() is not None:
                    print("房间"+str(room_list[index])+"已经结束")
                    new_rooms.remove(new_room)
                    room_list.remove(room_list[index])
            # 从数据中解包玩家人数
            playerNum = struct.unpack('i', data[:4])[0]
            
            if playerNum==100:
                concatenated_data=b''
                for hostName in room_list:
                    concatenated_data += struct.pack('i', hostName)
                await websocket.send(concatenated_data)
                continue
            print('请求的房间人数：'+str(playerNum))
            # 从端口中抽取未被占用的端口号
            roomHost=None
            for host in PublicHostList:
                if host in room_list:
                    continue
                else:
                    roomHost=host
                    room_list.append(host)
            if roomHost is None:
                print('端口已满')
                # 发0
                await websocket.send(struct.pack('i', 0))
                continue
            else:
                # 发送在线的房间号
                concatenated_data=b''
                for hostName in room_list:
                    concatenated_data += struct.pack('i', hostName)
                await websocket.send(concatenated_data)
                new_room=subprocess.Popen(['python3', 'roomServer.py'] + [str(playerNum),str(roomHost)])
                new_rooms.append(new_room)
        
            
    except websockets.exceptions.ConnectionClosed:
        print("连接已关闭")

# 启动WebSocket服务器的异步函数
async def main():
    # 启动WebSocket服务器
    async with websockets.serve(echo, "0.0.0.0", 3389):
        # 保持服务器运行
        await asyncio.Future()

# 运行WebSocket服务器
asyncio.run(main())
